byId = function(id) {
  return document.getElementById(id);
};

var appGoodClassification = new Vue({
  el: "#app-good-classification",
  data: {
    categories: [],
    editables: [],
    addedCategory2: []
  },
  methods: {
    getBlock: function(index) {
      return "block" + index;
    },
    getEditable: function(index) {
      return this.editables[index];
    },
    addItem: function(editable, category1) {
      Ply.dialog("prompt", {
        title: "添加",
        form: { name: "名称" }
      }).done(function(ui) {
        appGoodClassification.addedCategory2.push({
          category1_ID: category1.category1_ID,
          name: ui.data.name
        });
        var el = document.createElement("li");
        el.innerHTML = ui.data.name /*+ '<i class="js-remove">✖</i>'*/;
        editable.el.appendChild(el);
      });
    },
    resetCategories: function() {
      location.reload();
    },
    submitCategories: function() {
      //console.log(this.addedCategory2);
      Ply.dialog("confirm", "确定提交?").done(function() {
        console.log("submit: " + appGoodClassification.addedCategory2);
        for (let cate of appGoodClassification.addedCategory2) {
          Vue.http.post(SERVER_PORT + "addCategory2", {
            category1_ID: cate.category1_ID,
            name: cate.name
          }, {emulateJSON: true}).then(res => {
            console.log(res);
            if (res.ok && res.data.status === 1) {
              Ply.dialog("alert", "提交成功！");
            } else {
              Ply.dialog("alert", "数据提交失败，请刷新页面");
            }
          });    
        }
      });
    }
  },
  watch: {
    categories: function() {
      this.$nextTick(function() {
        let tempEditables = [];
        for (let i = 0; i < this.categories.length; i++) {
          let tempEditable = Sortable.create(eval("this.$refs.block"+i)[0], {
            animation: 150,
            filter: ".js-remove",
            onFilter: function(evt) {
              evt.item.parentNode.removeChild(evt.item);
            }
          })
          tempEditables.push(tempEditable);
        }
        appGoodClassification.editables = Object.assign({}, tempEditables);
      });
    }
  },
  mounted: function() {
    this.$http.get(SERVER_PORT + "requestCategory.php").then(res => {
      console.log(res);
      if (res.ok) {
        this.categories = Object.assign([], res.body.data);
      } else {
        alert("数据请求失败，请刷新页面");
      }
    });
  }
});
